import { localStorageTokenKey } from "context/auth-context";
import qs from "qs";
import { useCallback } from "react";

const apiUrl = process.env.REACT_APP_API_URL;

interface Config extends RequestInit {
  token?: string | null;
  data?: object;
}

export const http = async (
  endpoint: string,
  { data, token, headers, ...customConfig }: Config = {}
) => {
  const config = {
    method: "GET",
    headers: {
      Authorization: token ? token : "",
      "Content-type": data ? "application/json" : "",
    },
    ...customConfig,
  };

  const RESPONSE_STATUS_OK = 0;

  if (config.method.toUpperCase() === "GET") {
    endpoint += `?${qs.stringify(data)}`;
  } else {
    config.body = JSON.stringify(data || {});
  }
  return window
    .fetch(`${apiUrl}/${endpoint}`, config)
    .then(async (response) => {
      if (response.status === 401) {
        return Promise.reject({ message: "没有权限" });
      }

      const data = await response.json();
      if (response.ok) {
        if (data.error_code !== RESPONSE_STATUS_OK) {
          return Promise.reject({ message: data.message });
        }
        return data.data;
      }
    });
};

export const getToken = () => {
  return window.localStorage.getItem(localStorageTokenKey);
};

export const useHttp = () => {
  const token = getToken();

  return useCallback(
    (...[endpoint, config]: Parameters<typeof http>) =>
      http(endpoint, { ...config, token }),
    [token]
  );
};
